import sys
from main_ui import Ui_MainWindow
from uartPlain import Uart
from mac import Mac
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.QtCore import *
from PyQt5 import QtCore
from PyQt5 import QtGui
from suds.client import Client
import config
import excelSave
from WebserviceSuds import WebserviceSuds


class MyMainUi(QMainWindow, Ui_MainWindow):
    # 带两个参数(整数,字符串)的信号
    Signal_TwoParameters = pyqtSignal(str, str)
    sendList = ["m", "n", "l", "a", "b", "c", "d", "e", "a", "o"]
    sendListPQC = ["m", "n", "l", "a", "b", "c", "d", "e", "a", "o"]
    index = 0
    CARDRESULT = True
    PQCRESULT = True
    NOTGETRESULT = True
    HASlOGIN = False

    def __init__(self):
        super(MyMainUi, self).__init__()
        self.myUart = Uart(self.Signal_TwoParameters)
        self.setupUi(self)
        self.treeWidget.clicked.connect(self.onClicked)
        self.stackedWidget.setCurrentIndex(0)
        self.open.clicked.connect(self.openPort)
        self.start1.clicked.connect(self.startCardTest)
        self.start2.clicked.connect(self.startPqcTest)
        self.setMac.clicked.connect(self.setMacSn)
        self.send.clicked.connect(self.sendPlain)
        self.dispatch.clicked.connect(self.getDispatch)
        self.enter.clicked.connect(self.login)
        if config.needLogin() is False:  # 如果不需要登录
            self.HASlOGIN = True
            self.stackedWidget.setCurrentIndex(1)
        else:
            self.label_port.setVisible(False)
            self.comboBox.setVisible(False)
            self.open.setVisible(False)
            self.mes = config.getMes()
            self.editWorking.setText(self.mes.working)
            self.editItem.setText(self.mes.item)
            self.editClass.setText(self.mes.classes)
            self.editmaker.setText(self.mes.maker)
            self.editIP.setText(self.mes.ip)
            self.editWorking.setFocusPolicy(QtCore.Qt.NoFocus)
            self.editItem.setFocusPolicy(QtCore.Qt.NoFocus)
            self.editClass.setFocusPolicy(QtCore.Qt.NoFocus)
            self.editmaker.setFocusPolicy(QtCore.Qt.NoFocus)
            self.editIP.setFocusPolicy(QtCore.Qt.NoFocus)

    def login(self):  # 登录
        if self.dispatchCom.currentText() == "":
            QMessageBox.about(self, "提示", "请先获取调度号!")
            return
        web = WebserviceSuds(self.Signal_TwoParameters)
        web.check(self.editmaker.toPlainText())

    def loginResult(self, data):
        if data == self.editmaker.toPlainText():
            self.HASlOGIN = True
            self.mes.disptch = self.dispatchCom.currentText()
            self.stackedWidget.setCurrentIndex(1)
            ret = self.myUart.DOpenPort(self.mes.portname, 115200, None)
            if (ret == True):
                self.myUart.sendShell("getMacResult", "sucess", "FAIL", "/zr_bin/get_mac.sh")
                self.open.setText("关闭串口")
                QMessageBox.about(self, "提示", "打开串口成功!")
            else:
                QMessageBox.about(self, "提示", "打开串口失败,请检查配置和设备!")
        else:
            QMessageBox.about(self, "提示", "员工信息有误!请重新配置")

    def getDispatch(self):
        web = WebserviceSuds(self.Signal_TwoParameters)
        web.getDispatch(self.numEdit.toPlainText())

    def setDispatch(self, data):
        list = data.split(",")
        self.dispatchCom.clear()
        for i in range(0, len(list)):
            self.dispatchCom.addItem(list[i])

    def onClicked(self, qmodeLindex):  # 树形tab
        if self.HASlOGIN is False:
            QMessageBox.about(self, "提示", "请先登录!")
            return
        item = self.treeWidget.currentItem()
        if item.text(0) == '板卡测试':
            if self.stackedWidget.currentIndex() != 1:
                self.stackedWidget.setCurrentIndex(1)
        elif item.text(0) == '整机PQC':
            if self.stackedWidget.currentIndex() != 2:
                if self.NOTGETRESULT:
                    self.myUart.sendShell("hotResult", "NOHAVE", "", "cat /root/factory_test.log")
                self.stackedWidget.setCurrentIndex(2)

    def getPortList(self):  # 获取串口号
        port_list = self.myUart.GetPortList();
        self.comboBox.clear()
        for i in range(0, len(port_list)):
            self.comboBox.addItem(port_list[i].device)

    def openPort(self):  # 打开串口
        if self.open.text() == ("打开串口"):
            if self.comboBox.currentText() == "":
                QMessageBox.about(self, "提示", "没有可以打开的串口!")
                self.getPortList()
                return
            ret = self.myUart.DOpenPort(self.comboBox.currentText(), 115200, None)
            if (ret == True):
                self.myUart.sendShell("getMacResult", "sucess", "FAIL", "/zr_bin/get_mac.sh")
                self.open.setText("关闭串口")
                QMessageBox.about(self, "提示", "打开串口成功!")
            else:
                QMessageBox.about(self, "提示", "打开串口失败!")
        else:
            self.open.setText("打开串口")
            self.myUart.DColsePort()

    def closeEvent(self, a0: QtGui.QCloseEvent) -> None:  # 关闭窗口
        self.myUart.DColsePort()

    def startCardTest(self):  # 板卡测试
        if self.myUart.isNotOpen():
            QMessageBox.about(self, "提示", "请先打开串口!")
            return
        if self.mac.text() == "" or self.sn.text() == "":
            QMessageBox.about(self, "提示", "请先设置mac sn!")
            return
        lables = [self.cardNetTest, self.cardEnTest, self.cardPortTest, self.cardRtcTest, self.card4GTest,self.cardResult]
        for lable in lables:
            self.setTextBegin(lable)
        self.index = 0
        self.myUart.sendShell("cardTestResult", "chose:", "FAIL", "/zr_bin/factory")

    def startPqcTest(self):  # pqc测试
        if self.myUart.isNotOpen():
            QMessageBox.about(self, "提示", "请先打开串口!")
            return
        if self.mac.text() == "" or self.sn.text() == "":
            QMessageBox.about(self, "提示", "未获取到sn、mac 正在重新获取!")
            self.myUart.sendShell("getMacResult", "sucess", "FAIL", "/zr_bin/get_mac.sh")
            return
        lables = [self.pqcNetTest, self.pqcEnTest, self.pqcPortTest, self.pqcRtcTest, self.pqc4GTest,self.pqcResult]
        for lable in lables:
            self.setTextBegin(lable)
        self.index = 0
        self.myUart.sendShell("pqcTestResult", "chose:", "FAIL", "/zr_bin/factory")

    def sendPlain(self):  # 底部发送
        if self.myUart.isNotOpen():
            QMessageBox.about(self, "提示", "请先打开串口!")
            return
        self.myUart.sendShell("showBottom", "sucess", "FAIL", self.editSend.toPlainText())

    def setMacSn(self):  # set mac
        if self.myUart.isNotOpen():
            QMessageBox.about(self, "提示", "请先打开串口!")
            return
        editget = self.editMac.toPlainText()
        sn = self.editSn.toPlainText()
        if editget == "" or sn == "":
            QMessageBox.about(self, "提示", "请输入mac和sn!")
            return
        ret = editget.find(":")
        if len(editget) != 12:
            QMessageBox.about(self, "提示", "MAC应为12位!")
            return
        if len(sn) < 14:
            QMessageBox.about(self, "提示", "SN长度必须大于13!")
            return
        yes = QMessageBox.Yes
        if self.sn.text() != "" and self.mac != "" and self.mac_2 != "":
            yes = QMessageBox.question(self, "提示", "存在mac、sn，确认继续？", QMessageBox.Yes | QMessageBox.No)
        if yes == QMessageBox.Yes:
            mac1 = ""
            for index in range(len(editget)):
                mac1 += editget[index]
                a = index + 1
                if a % 2 == 0 and a != 12:
                    mac1 += ":"

            a = int(mac1[len(mac1) - 2:len(mac1)], 16)
            a = a + 1
            result = hex(a)
            if len(result) > 2:
                result = result[2:4]
            if len(result) == 1:
                result = "0"+result
            mac2 = mac1[0:len(mac1) - 2] + result
            mac = config.getMac()
            mac.product_mac1 = mac1
            mac.product_mac2 = mac2
            mac.product_sn = sn
            self.myUart.sendShell("setMacResult", "sucess", "FAIL", "/zr_bin/set_mac.sh " + str(mac.getString()))

    def threadUi(self, shellid, data):  # 接受子线程消息 槽函数
        exist = hasattr(self, str(shellid))
        if exist:
            f = getattr(self, str(shellid))  # 使用getattr函数去寻找字符串的同名方法
            f(data)  # 调用方法

    def getMacResult(self, data):  # get mac
        list = data.split()
        mac = Mac()
        for c in list:
            one = c.split("=")
            if len(one) == 2:
                f = setattr(mac, one[0], one[1])
        self.sn.setText(mac.product_sn)
        self.name.setText(mac.product_name)
        self.ver.setText(mac.product_hard_version)
        self.id.setText(mac.product_id)
        self.mac.setText(mac.product_mac1)
        self.mac_2.setText(mac.product_mac2)

    def setMacResult(self, data):  # set mac result
        self.showBottom("设置成功")
        self.myUart.sendShell("getMacResult", "sucess", "FAIL", "/zr_bin/get_mac.sh")
        QMessageBox.about(self, "提示", "设置成功!")

    def cardTestResult(self, data):  # 板卡测试结果
        if self.index == 0:
            self.showBottom("开始测试:")
        else:
            self.showBottom(data)
        self.cartTestUI(data)
        if self.index < len(self.sendList):
            self.myUart.sendShell("cardTestResult", "PASS", "FAIL", self.sendList[self.index])
            self.showBottom(self.sendList[self.index])
            self.index = self.index + 1
        else:
            self.myUart.sendShell("00", "", "", "q")
            self.sendMes()
            if self.CARDRESULT:
                self.setTextWithColor(self.cardResult, "PASS")
            else:
                self.setTextWithColor(self.cardResult, "FAIL")
                self.saveCardErrorInfo()

    def pqcTestResult(self, data):  # pqc测试结果
        if self.index == 0:
            self.showBottom("开始测试:")
        else:
            self.showBottom(data)
        self.pqcTestUI(data)
        if self.index < len(self.sendList):
            self.myUart.sendShell("pqcTestResult", "PASS", "FAIL", self.sendListPQC[self.index])
            self.showBottom(self.sendListPQC[self.index])
            self.index = self.index + 1
        else:
            self.myUart.sendShell("00", "", "", "q")
            self.sendMes()
            if self.PQCRESULT:
                self.setTextWithColor(self.pqcResult, "PASS")
            else:
                self.setTextWithColor(self.pqcResult, "FAIL")
                self.savePqcErrorInfo();

    def sendMes(self):
        if config.needLogin():
            web = WebserviceSuds(self.Signal_TwoParameters)
            self.mes.sn = self.sn.text()
            web.sendMes(self.mes)

    def mesResult(self, data):
        QMessageBox.about(self, "提示", "抛mes失败!")
        self.showBottom(data)

    def hotResult(self, data):  # 烤机结果
        self.NOTGETRESULT = False
        list = data.split("test")
        print(list)
        for c in list:
            sIndex = c.find("sucess")
            if sIndex > 0:
                fIndex = c.find("fail")
                sNum = int(c[sIndex + 7:fIndex])
                fNum = int(c[fIndex + 5:fIndex + 15])
                name = c[fIndex + 25:len(c)]
                result = "PASS"
                if 9 * fNum - sNum > 0:
                    result = "FAIL"
                print(str(sNum) + "|" + str(fNum) + "|" + name + "|" + result)
                try:
                    if "eth" in name:
                        self.setTextWithColor(self.hotNet, result)
                    elif "hs" in name:
                        self.setTextWithColor(self.hotEn, result)
                    elif "uart" in name:
                        self.setTextWithColor(self.hotPort, result)
                    elif "rtc" in name:
                        self.setTextWithColor(self.hotRtc, result)
                    elif "ppp" in name:
                        self.setTextWithColor(self.hot4G, result)
                except Exception as e:
                    print("---异常---：", e)

    def showTip(self, data):
        QMessageBox.about(self, "提示", data)

    def showTipClose(self, data):
        QMessageBox.about(self, "提示", data)
        if "设备" in data:
            self.open.setText("打开串口")
            self.getPortList()

    def cartTestUI(self, text):
        if text == "FAIL":
            self.CARDRESULT = False
        if self.index == 0:
            return
        if self.index <= 2:
            self.setTextWithColor(self.cardNetTest, text)
        elif self.index <= 3:
            self.setTextWithColor(self.cardEnTest, text)
        elif self.index <= 8:
            self.setTextWithColor(self.cardPortTest, text)
        elif self.index <= 9:
            self.setTextWithColor(self.cardRtcTest, text)
        elif self.index <= 10:
            self.setTextWithColor(self.card4GTest, text)

    def pqcTestUI(self, text):
        if text == "FAIL":
            self.PQCRESULT = False
        if self.index == 0:
            return
        if self.index <= 2:
            self.setTextWithColor(self.pqcNetTest, text)
        elif self.index <= 3:
            self.setTextWithColor(self.pqcEnTest, text)
        elif self.index <= 8:
            self.setTextWithColor(self.pqcPortTest, text)
        elif self.index <= 9:
            self.setTextWithColor(self.pqcRtcTest, text)
        elif self.index <= 10:
            self.setTextWithColor(self.pqc4GTest, text)

    def setTextWithColor(self, lable, text):
        if lable.text() != "FAIL":
            lable.setText(text)
            if text == "PASS":
                lable.setStyleSheet("color:rgb(0,100,0)")
            if text == "FAIL":
                lable.setStyleSheet("color:rgb(255,0,0)")

    def setTextBegin(self, lable):
        lable.setText("UNKNOW")
        lable.setStyleSheet("")

    def showBottom(self, data):  # 底部show
        self.editshow.append(data)

    def saveCardErrorInfo(self):
        lables = [self.cardNetTest, self.cardEnTest, self.cardPortTest, self.cardRtcTest, self.card4GTest]
        str = ""
        for lable in lables:
            if lable.text() == "FAIL":
                str = str + lable.objectName() + ","
        if str != "":
            str = str[0:len(str) - 1]
            data = [self.sn.text(), self.mac.text(), str]
            excelSave.addOneLine(data)

    def savePqcErrorInfo(self):
        lables = [self.pqcNetTest, self.pqcEnTest, self.pqcPortTest, self.pqcRtcTest, self.pqc4GTest]
        str = ""
        for lable in lables:
            if lable.text() == "FAIL":
                str = str + lable.objectName() + ","
        if str != "":
            str = str[0:len(str) - 1]
            data = [self.sn.text(), self.mac.text(), str]
            excelSave.addOneLine(data)


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ui = MyMainUi()
    ui.Signal_TwoParameters[str, str].connect(ui.threadUi)  # 连接信号
    ui.show()
    ui.getPortList()
    sys.exit(app.exec_())
